import {
  inventoryDetailsPageApi,
  inventoryApi,
  inventoryAllApi
} from '@/api/workflow/inventory'
import { Ref } from 'vue'
import { ProTableInst } from '@/components/pro-table/type'
import { PageRequest } from '@/api/types'
import { InventoryModel } from '@/api/model/inventory-model'
import { userInfo } from '~/types/user'
import { userInfoModel } from '@/api/model/userModel'
import dayjs from 'dayjs'

type Props = {
  title: string
  code: string
  userInfo: Ref<userInfo<userInfoModel>>
  proTableInst: Ref<ProTableInst | null>
}

export const useInventoryApi = ({
  title,
  code,
  proTableInst,
  userInfo
}: Props) => {
  const confirmLoading = ref(false)

  // 获取盘点详情列表
  const fetchInventoryDetailsPage = async (
    pageRequest: PageRequest,
    queryParams: InventoryModel
  ) => {
    const res = await inventoryDetailsPageApi({
      ...queryParams,
      orgId: userInfo.value.orgId,
      code,
      pageRequest
    })

    if (res.code === '0000') {
      return {
        data: res.data?.content,
        total: res.data?.total
      }
    }
  }

  const fetchInventory = async (row: any, status: string) => {
    const data = {
      ...row,
      inventoryAssetStatus: status,
      inventoryCode: code,
      branchName: userInfo.value.orgName,
      branchId: userInfo.value.orgId,
      title,
      inStoreDate: dayjs().format('YYYY-MM-DD')
    }
    const res = await inventoryApi(data)
    if (res.code === '0000') {
      useMsg('success', '盘点成功')
      proTableInst.value?.reload()
    }
  }

  // 整单完成
  const fetchInventoryAll = async () => {
    const data = {
      inventoryCode: code
    }
    const res = await inventoryAllApi(data)
    if (res.code === '0000') {
      useMsg('success', '整单盘点成功')
      proTableInst.value?.reload()
    }
  }

  return {
    fetchInventoryDetailsPage,
    fetchInventory,
    fetchInventoryAll,
    confirmLoading
  }
}
